package com.yunxi.core.web;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class DateJsonDeserializer extends JsonDeserializer<Date> {
    public static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static final SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
    public static final SimpleDateFormat format3 = new SimpleDateFormat("yyyyMMdd");
    public static final SimpleDateFormat format_iview = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");

    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
            throws IOException {
        try {
            String aaa = jsonParser.getText();
            if (StringUtils.isNotEmpty(aaa)) {
                if (aaa.length() == 10) {
                    return format2.parse(jsonParser.getText());
                } else if (aaa.indexOf("T") != -1 && aaa.indexOf("Z") != -1) {
                    format_iview.setTimeZone(TimeZone.getTimeZone("ETC/GMT-8"));
                    return format_iview.parse(jsonParser.getText());
                } else if (aaa.indexOf("T") != -1 && aaa.indexOf("Z") == -1) {
                    format_iview.setTimeZone(TimeZone.getTimeZone("ETC/GMT-8"));
                    return format_iview.parse(jsonParser.getText());
                }
                else {
                    if(aaa.length()==8){
                        return format3.parse(jsonParser.getText());
                    }else{
                        return format.parse(jsonParser.getText());
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new RuntimeException(e);
        }
        return null;
    }
} 